﻿
var totalCount = 0;
var pageIndex = 1;
var pageSize = 100;
//仓库下拉框
layui.use('form', function () {
    var form = layui.form;
    $.ajax({
        url: "/Warehouse/GetWarehouseLShow",
        type: "get",
        data: { token: localStorage.getItem("token") },
        success: function (data) {
            var data = JSON.parse(data)
            console.log(data.data)
            var options = '<option value="">请选择</option>'; // 添加默认选项
            $.each(data.data, function (index, item) {
                options += '<option value="' + item.warehouseId + '">' + item.warehouseName + '</option>';
            });
            $("#warehouseId").html(options);
            form.render('select'); // 重新渲染下拉框
        },
        error: function () {
            console.log("获取数据失败");
            // 可以考虑显示一个错误消息给用户
        }
    });
});

//库位显示
function show() {
    layui.use('table', function () {
        var table = layui.table;
        var laypage = layui.laypage;

        //查询
        var binLocationNo = $("#binLocationNo").val();
        var binLocationName = $("#binLocationName").val();
        var warehouseId = $("#warehouseId").val();
        $.ajax({
            url: "/Warehouse/GetBinLocationShow",
            type: "get",
            data: {
                binLocationNo: binLocationNo,
                binLocationName: binLocationName,
                warehouseId: warehouseId || 0,
                pageIndex: pageIndex,
                pageSize: pageSize,
                token: localStorage.getItem("token"),
            },
            success: function (res) {
                //console.log(res)
                var res = JSON.parse(res)
                if (res.code === 0) {
                    console.log(res.data.list)
                    table.render({
                        elem: '#binLocationData',//对应HTML中表格的id
                        data: res.data.list,//绑定获取的数据
                        toolbar: '#toolbarDemo',//导出
                        defaultToolbar: ['exports'],//导出
                        cols: [[
                            { type: 'checkbox', fixed: 'left' },
                            { field: 'binLocationNo', title: '库位编号', width: 160 },
                            { field: 'binLocationName', title: '库位名称', width: 130 },
                            { field: 'warehouseLocationName', title: '库位类型', width: 110 },
                            { field: 'warehouseName', title: '仓库', width: 110 },
                            {
                                field: 'isDisable', title: '是否禁用', width: 80, templet: function (d) {
                                    if (d.isDisable === false) {
                                        return '<span>否</span>';
                                    } else {
                                        return '<span>是</span>';
                                    }
                                }
                            },
                            {
                                field: 'isDefault', title: '是否默认', width: 80, templet: function (d) {
                                    if (d.isDefault === false) {
                                        return '<span>否</span>';
                                    } else {
                                        return '<span>是</span>';
                                    }
                                }
                            },
                            {
                                field: 'createTime', title: '创建时间', templet: function (d) {
                                    return formatTime(d.createTime);
                                }, width: 170
                            },
                            { field: 'binLocationRemarks', title: '备注', width: 80 },
                            {
                                field: '', title: '操作', templet: function (d) {
                                    return '<a class="layui-btn layui-btn-edit layui-btn-xs" lay-on="test-page-edit" onclick="updateData(' + d.binLocationId + ')"><i class="layui-icon layui-icon-edit"></i>编辑</a> ' +
                                        '<a class="layui-btn layui-btn-danger layui-btn-xs" onclick="deleteData(' + d.binLocationId + ')"><i class="layui-icon layui-icon-delete"></i>删除</a>';
                                }
                            }
                        ]],
                        page: true, // 是否显示分页
                        count: res.data.totalCount,
                        limits: [3, 6, 8],
                        limit: 3,// 每页默认显示的数量
                        curr: pageIndex,
                    });

                } else {
                    console.log(res.msg);
                }
                //console.log(totalCount)

            },
            error: function () {
                console.log("获取数据失败");
                // 可以考虑显示一个错误消息给用户
            }
        });
    });
}

window.deleteData = function (binLocationId) {
    layer.confirm('确定要删除该条数据吗？', function (index) {
        console.log(binLocationId)
        var binLocationIds = {
            binLocationId: binLocationId
        }
        console.log(binLocationIds)
        $.ajax({
            type: "post",
            url: "/Warehouse/GetDelectBinLocation",  
            data: {
                binLocationIds: binLocationIds,
                token: localStorage.getItem("token"),
            },
            success: function (res) {
                var obj = JSON.parse(res)
                if (obj.code === 1) {
                    layer.alert("删除成功");
                    show();  // 重新加载数据，刷新表格显示
                    console.log(obj.code)
                } else {
                    layer.alert("删除失败");
                }
            },
            error: function () {
                layer.msg('删除失败，请稍后重试', {
                    time: 2000,
                    icon: 2
                });
            }
        });
        layer.close(index);
    });
};
//库位批量删除
$('#batchDeleteButton').click(function () {
    var table = layui.table;
    // 获取选中行的数据（这里主要是获取warehouseId）
    var checkStatus = table.checkStatus('binLocationData');
    var selectedData = checkStatus.data.map(function (item) {
        return item.binLocationId;
    });

    if (selectedData.length === 0) {
        layer.msg("请至少选择一条要删除的数据", { icon: 2 });
        return;
    }

    console.log(selectedData);
    layer.confirm('确定要批量删除选中的' + selectedData.length + '条数据吗？', function (index) {
        var binLocationIds = {
            binLocationId: selectedData
        }
        // 发送批量删除请求到后端
        $.ajax({
            url: "/Warehouse/GetPlDelectBinLocation", // 后端处理批量删除的接口地址，需根据实际情况调整
            type: "post",
            // contentType: "application/json",
            data: {
                binLocationIds: binLocationIds,
                token: localStorage.getItem("token"),
            },
            success: function (res) {
                var res = JSON.parse(res)
                console.log(res.code);
                if (res.code > 0) {
                    layer.msg("批量删除成功", { icon: 1 })
                    // 重新加载表格数据，展示更新后的列表
                    show();
                } else {
                    layer.msg("批量删除失败:" + res.message, { icon: 2 });
                }
            },
            error: function () {
                console.log("批量删除数据失败");
                // 可以考虑显示一个错误消息给用户
            }
        });
    })
})

// 点击编辑按钮的事件处理
$('#batchUpdBtn').click(function () {
    var table = layui.table;
    // 获取选中行的数据（这里主要是获取warehouseId）
    var checkStatus = table.checkStatus('binLocationData');
    var selectedData = checkStatus.data.map(function (item) {
        return item.binLocationId;
    });
    console.log(selectedData);
    if (selectedData.length === 0) {
        layer.msg("请选择一条要编辑的数据", { icon: 2 });
        return;
    }
    localStorage['binLocationId'] = selectedData;
    location.href = '/Warehouse/BinLocationUpd';
});
//仓库编辑
window.updateData = function (binLocationId) {
    localStorage['binLocationId'] = binLocationId;
    location.href = '/Warehouse/BinLocationUpd';
}
// //文档就绪函数
$(function () {
    show();
})
//时间格式
function formatTime(timeStamp) {
    if (timeStamp) {
        var date = new Date(timeStamp);
        var year = date.getFullYear(); // 获取年份
        var month = ('0' + (date.getMonth() + 1)).slice(-2); // 获取月份，+1是因为getMonth()返回的月份是从0开始计数的
        var day = ('0' + date.getDate()).slice(-2); // 获取日期
        var hour = ('0' + date.getHours()).slice(-2); // 获取小时
        var minute = ('0' + date.getMinutes()).slice(-2); // 获取分钟
        var second = ('0' + date.getSeconds()).slice(-2); // 获取秒
        return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
    }
    return "";
}